let jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {

        //白名单
        let writeArr = ['/api/login','/api/registry'];

        if(writeArr.includes(ctx.request.url)){
            //不用校验
            await next();
        }else{
            let token = ctx.get('token') //从header内获取token 或   ctx.request.headers.token
            
            try{
                jwt.verify(token,'lixd');
                await next();
            }catch(e){
                //token 有误  或其他的报错
                if(e.name === 'JsonWebTokenError' || e.name === 'TokenExpiredError'){
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:'鉴权失败'
                    }
                }else{
                    ctx.body = {
                        code:5,
                        msg:e
                    }
                }
            }
        }
    }
}